/**
 * 
 */
package co.com.ebusiness.trader.pages;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;

import co.com.ebusiness.trader.services.TraderService;

/**
 * @author Luis Agudelo
 *
 */
public class ActualizarPrecio {

	
		// Screen fields
		@Property
		private co.com.ebusiness.trader.model.Precio precio;
		
		// Other pages
		@InjectPage
		private Precio indexPage;

		// Generally useful bits and pieces

		@Component(id = "precioForm")
		private BeanEditForm precioForm;

		@Inject
		private TraderService traderService;

		
		// onPassivate() is called by Tapestry to get the activation context to put in the URL.

		co.com.ebusiness.trader.model.Precio onPassivate() {
			return precio;
		}
		
		// onActivate() is called by Tapestry to pass in the activation context from the URL.
		void onActivate(co.com.ebusiness.trader.model.Precio precio) {
			this.precio = precio;
		}

		// PersonForm bubbles up the PREPARE_FOR_SUBMIT event during form submission.
		void onPrepareForSubmit() {
			// Get objects for the form fields to overlay.
			precio = traderService.getPrecio(precio.getIdPrec());
			
			if (precio == null) {
				precio = new co.com.ebusiness.trader.model.Precio();
				precioForm.recordError("El precio ha sido borrado.");
			}
		}

		// PersonForm bubbles up the VALIDATE event when it is submitted
		@CommitAfter
		void onValidateFromPrecioForm() {

			if (precioForm.getHasErrors()) {
				// We get here only if a server-side validator detected an error.
				return;
			}

			try {
				traderService.guardarPrecio(precio);
			}
			catch (Exception e) {
				// Display the cause. In a real system we would try harder to get a user-friendly message.
				precioForm.recordError(e.getMessage());
			}
		}

		// PersonForm bubbles up SUCCESS or FAILURE when it is submitted, depending on whether VALIDATE records an error

		Object onSuccess() {
			return indexPage;
		}
		
}
